import React, {useCallback} from 'react';
import {Pagination,Button, Card, DatePicker, Dialog, Field, Icon, Input, List, Message, Select, Table} from '@alifd/next';
import {useFusionTable, useSetState} from 'ahooks';
import {request,Link} from 'ice'
import moment, {Moment} from 'moment';
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';
import DialogOperation from './DialogOperation';
import {ActionType, OperaitionProps} from './Operation';
import styles from './index.module.scss';
// @ts-ignore
import Img from '@icedesign/img';
import Qrcode, { Panel } from '@icedesign/qrcode';


const {RangePicker, MonthPicker, YearPicker, WeekPicker} = DatePicker;

interface ColumnWidth {
  name: number;
  email: number;
  phone: number;
  gender: number;
  operation: number;
}

interface DialogState {
  columnWidth: ColumnWidth;
  optCol: any;
  actionType: ActionType;
  actionVisible: boolean;
}

const defaultColumnWidth: ColumnWidth = {
  name: 140,
  email: 500,
  phone: 400,
  gender: 140,
  operation: 150,
};


const DialogTable: React.FC = () => {
  moment.locale('zh-cn');

  const [dShow, setDShow] = useSetState({
    show:false,
    source:{},
    jwt:''
  });

  // 记录选择的日期 moment().subtract(1,'weeks'),moment()
  const [searchDate, setSearchDate] = useSetState<Moment[]>([moment().subtract(1, 'weeks'), moment()]);
  const [queryState, setQueryState] = useSetState({
    channelNum: undefined,
    queryChannel: false,
    queryChannelTotal: false,
    date: Math.floor(moment(searchDate[0]).valueOf() / 1000),
    date2: Math.floor(moment(searchDate[1]).valueOf() / 1000)
  });

  const getTableData = (
    {current, pageSize}: { current: number; pageSize: number },
    formData: { status: 'normal' | 'empty' | 'exception' }
  ): Promise<any> => {
    if (!formData.status || formData.status === 'normal') {
      let query = `current=${current}&size=${pageSize}`;
      Object.entries(formData).forEach(([key, value]) => {
        if (value) {
          query += `&${key}=${value}`
        }
      });
      const moment1 = searchDate && searchDate[0] && searchDate[1];
      if (!moment1) {
        return Promise.resolve([]);
      }
      const data = request({
        url: `/v1/movie/ticket/?${query}`,
        method: 'get',
        params: queryState
      });
      return data.then(res => {
        return {
          list: res.data.list,
          total: res.data.count
        }
      })
    }
    if (formData.status === 'empty') {
      return Promise.resolve([]);
    }
    if (formData.status === 'exception') {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(new Error('data exception'));
        }, 1000);
      });
    }

    return Promise.resolve([]);
  };


  const [state, setState] = useSetState<DialogState>({
    columnWidth: defaultColumnWidth,
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
  });
  const {actionVisible, columnWidth, optCol} = state;
  const field = Field.useField([]);
  const {paginationProps, tableProps, search, error, refresh} = useFusionTable(getTableData, {
    field,
  });

  const {reset} = search;
  const onResizeChange = (dataIndex: keyof typeof defaultColumnWidth, width: number) => {
    const newWidth = {
      ...columnWidth,
    };
    newWidth[dataIndex] += width;
    setState({columnWidth: newWidth});
  };

  const operationCallback = useCallback(({actionType, dataSource}: OperaitionProps): void => {
    setState({
      actionType,
      optCol: dataSource,
      actionVisible: true,
    });
  }, [setState]);

  const handleCancel = useCallback((): void => {
    setState({actionVisible: false});
  }, [setState]);

  const handleOk = useCallback((): void => {
    const {actionType} = state;
    if (actionType === 'preview') {
      handleCancel();
      return;
    }
    Message.success(actionType === 'add' ? '添加成功!' : '编辑成功!');
    reset();
    handleCancel();
  }, [handleCancel, reset, state]);

  const handleDelete = useCallback((data: any) => {
    if (!data) {
      return;
    }
    Dialog.confirm({
      title: '删除提醒',
      content: `确定删除 ${data.name.last} 吗`,
      onOk() {
        Message.success(`${data.name.last} 删除成功!`);
        reset();
      }
    });
  }, [reset]);

  const cellC = (...args: any[]): React.ReactNode => {
    const record = args[2];
    // retained register watchCount
    if (record.login !== null) {
      if (record.login !== 0) {
        return `${(record.watchCount / record.login).toFixed(2)}`;
      }
    }
    return '';
  }

  const cellD = (...args: any[]): React.ReactNode => {
    const record = args[2];
    // retained register watchCount loginTime
    if (record.login !== null) {
      if (record.login !== 0 && record.loginTime !== 0) {
        return `${(record.loginTime / record.login).toFixed(2)}`;
      }
    }
    return '';
  }


  const cellB = (...args: any[]): React.ReactNode => {
    const record = args[2];
    // retained register
    if (record.register !== null && record.retained !== null) {
      if (record.register !== 0) {
        return `${(record.retained / record.register * 100).toFixed(2)}%`;
      }
    }
    return '';
  }
  const cellOperation = (...args: any[]): React.ReactNode => {
    const record = args[2];
    return (
      <div>
        <Button
          type="primary"
          disabled={record.tState==1||record.hasEnd}
          onClick={() => dOnOpen({actionType: 'edit', dataSource: record})}
        >
          {cast2(record)}
        </Button>
        &nbsp;&nbsp;
      </div>
    );
  };

  const cast2 =  (...args: any[]) => {
    const record = args[0];
    console.log(record);
    if(record?.hasEnd){
      return "放映结束"
    }
    if(record?.tState==1){
      return "已经验票"
    }else{
      return "验票二维码"
    }
  };

  const Option = Select.Option;


  const onChange = val => {
    if (val) {
      setQueryState({
        date: Math.floor(moment(val[0]).valueOf() / 1000),
        date2: Math.floor(moment(val[1]).valueOf() / 1000),
      });
    }
    setSearchDate(val);
    console.log(queryState);
  }

  const channelNumOnChange = val => {
    setQueryState({
      channelNum: val
    })
  }
  const queryChannelOnChange = val => {
    if (val === 1) {
      setQueryState({
        queryChannelTotal: true
      });
    } else {
      setQueryState({
        queryChannel: val,
        queryChannelTotal: false
      });
    }

  }


  const renderImg = value => {
    value = `${value}`;
    return <img width="500" height="250" src={value}/>;
  };

  const render1 =  (...args: any[]) => {
    const record = args[2];
    // console.log(record)
    return <div>{record.name}(时长{record.time}分)</div>;
  };

  const cast1 =  (...args: any[]) => {
    const record = args[2];
    // console.log(record);
    return record.startTime?.replace("T"," ")
  };

async function dOnOk(){
  if(dShow.jwt){
    const data = await request({
      url: `/v1/movie/ticket/inspect/`,
      method: 'post',
      data:{code:dShow.jwt}
    });
    if(data?.statusCode==200){
      Message.success('验票成功');
      dOnonClose();
      reset();
    }
  }
}

async function dGetInfo(value){
  const data = await request({
    url: `/v1/movie/ticket/code/${value?.tId}/`,
    method: 'get',
    data:dShow.source
  });
  console.log(dShow);
  if(data?.statusCode==200){
    setDShow({
      jwt:data.data.jwt
    })
  }
}

const dOnonClose = () => {
  setDShow({show:false})
}
const dOnOpen = value => {
  console.log(value.dataSource);
  setDShow({
    show:true,
    source:value.dataSource
  })
  dGetInfo(value.dataSource);
}

  return (

    <div className={styles.DialogTable}>


      <Dialog  
          title="验票码"
          visible={dShow.show}
          onOk={dOnOk}
          onCancel={dOnonClose}
          onClose={dOnonClose}>
           <Panel value={dShow.jwt} size={500} text="请出示扫描"/>
      </Dialog>

      <List header={<div>我的电影票</div>}>

      </List>
      <Card free>
        <Card.Content>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh}/> : <EmptyBlock/>}
            primaryKey="email"
          >
            <Table.Column title="电影名称" dataIndex="name" resizable width={columnWidth.email}/>
            {/* <Table.Column title="电影海报" dataIndex="icon" resizable width={columnWidth.phone} cell={renderImg}/> */}
            <Table.Column title="电影院" dataIndex="cmName" resizable width={columnWidth.email}/>
            <Table.Column title="电影厅" dataIndex="hName" resizable width={columnWidth.email} />
            <Table.Column title="详细地址" dataIndex="address" resizable width={columnWidth.email} />
            <Table.Column title="入场时间" dataIndex="startTime" resizable width={columnWidth.email} cell={cast1} />
            <Table.Column title="票价" dataIndex="price" resizable width={columnWidth.gender} />
            <Table.Column title="电影票状态" dataIndex="state" resizable width={columnWidth.email} />

            <Table.Column title="操作" resizable width={columnWidth.operation} cell={cellOperation}/>
          </Table>
          <Pagination pageSizeList={[10, 20]} pageSizeSelector="filter" 
          style={{ marginTop: 16, textAlign: 'right' }} totalRender={total => <>共 <Button text type="primary">{total}</Button> 个记录</>}  {...paginationProps} />
        </Card.Content>
      </Card>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
      />
    </div>
  );
}

export default DialogTable;
